package com.auto.printer.handler;

import cn.hutool.core.io.FileUtil;
import com.auto.printer.entity.dto.PdfConvertDTO;
import com.auto.printer.entity.param.QiNiuOssUploadBean;
import com.auto.printer.utils.QiNiuUtils;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import lombok.RequiredArgsConstructor;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author LoveHuaHua
 * @date 2023年08月01日 8:28
 * @description believe in yourself
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class DocxConvert implements IPdfConvert{

    private final QiNiuUtils ossUtil;
    /**
     * 转换
     *
     * @param fileUrl 文件地址
     * @param bytes   文件字节
     * @return {@link String}
     */
    @Override
    public PdfConvertDTO convert(String fileUrl, byte[] bytes) throws IOException {
        XWPFDocument xwpfDocument = new XWPFDocument(new ByteArrayInputStream(bytes));
        PdfOptions pdf = PdfOptions.create();
        Path outPutPath = Paths.get(FileUtil.getPrefix(fileUrl) + ".pdf");
        OutputStream os = Files.newOutputStream(outPutPath);
        PdfConverter.getInstance().convert(xwpfDocument, os, pdf);
        os.close();
        QiNiuOssUploadBean qiNiuOssUploadBean = ossUtil.uploadFileByStream(outPutPath.toFile());
        PDDocument load = PDDocument.load(outPutPath.toFile());

        return new PdfConvertDTO(load,qiNiuOssUploadBean.getUrl());
    }

    /**
     * 是否支持
     *
     * @param fileSuffix 文件后缀
     * @return boolean
     */
    @Override
    public boolean isSupport(String fileSuffix) {
        return "docx".equalsIgnoreCase(fileSuffix);
    }

    /**
     * 排序 越大优先级越大
     *
     * @return int
     */
    @Override
    public int sort() {
        return 1;
    }
}
